<template>
  <div class="pay-page">
    <el-header class="header" height="70px">
      <div class="header-content">
        <div class="logo">
          <h1 @click="$router.push('/')" style="cursor: pointer;">周周淘商城</h1>
        </div>
        <div class="nav-actions">
          <el-button @click="$router.push('/products')" type="primary" plain>
            继续购物
          </el-button>
          <template v-if="userStore.token">
            <el-dropdown @command="handleUserCommand">
              <el-button type="primary">
                {{ userStore.userInfo?.username || '用户' }}
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人中心</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </div>
      </div>
    </el-header>

    <el-main class="main-content">
      <el-card class="pay-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>订单支付</span>
            <span class="countdown">
              请在 <span class="time">{{ formattedTime }}</span> 内完成支付，逾期订单将自动取消
            </span>
          </div>
        </template>

        <div class="order-info">
          <h3>订单号：{{ orderId }}</h3>
          <p>支付金额：<span class="amount">¥{{ formattedAmount }}</span></p>
        </div>

        <el-divider>选择支付方式</el-divider>

        <div class="payment-options">
          <div
            class="payment-item"
            :class="{ 'selected': selectedPaymentType === 1 }"
            @click="selectPayment(1)"
          >
            <img :src="alipayLogo" alt="支付宝" class="payment-logo" />
            <span>支付宝支付</span>
            <el-icon v-if="selectedPaymentType === 1"><Check /></el-icon>
          </div>
          <div
            class="payment-item"
            :class="{ 'selected': selectedPaymentType === 2 }"
            @click="selectPayment(2)"
          >
            <img :src="wechatpayLogo" alt="微信支付" class="payment-logo" />
            <span>微信支付</span>
            <el-icon v-if="selectedPaymentType === 2"><Check /></el-icon>
          </div>
          <div
            class="payment-item"
            :class="{ 'selected': selectedPaymentType === 3 }"
            @click="selectPayment(3)"
          >
            <el-icon><Money /></el-icon>
            <span>余额支付</span>
            <el-icon v-if="selectedPaymentType === 3"><Check /></el-icon>
          </div>
        </div>

        <el-button
          type="primary"
          size="large"
          class="pay-button"
          :disabled="!selectedPaymentType"
          @click="handlePay"
        >
          确认支付
        </el-button>
      </el-card>
    </el-main>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, Check, Money } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { queryOrderDetail, type OrderDetailVO } from '@/api/order'
import { applyPayOrder, tryPayOrderByBalance, PayType } from '@/api/pay'
import alipayLogo from '@/assets/alipay.png'
import wechatpayLogo from '@/assets/wechat.png'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const orderId = ref<string>('')
const totalAmount = ref<number>(0) // 订单金额，单位为分
const remainingTime = ref(900) // 倒计时，单位秒 (15分钟)
let timer: number | undefined = undefined

const selectedPaymentType = ref<number | null>(null) // 1: 支付宝, 2: 微信, 3: 余额

const orderDetails = ref<OrderDetailVO[]>([]) // 存储订单详情

// 支付渠道编码映射
const payChannelCodeMap: Record<PayType, string> = {
  [PayType.ALIPAY]: 'ALI_PAY',
  [PayType.WECHAT_PAY]: 'WECHAT_PAY',
  [PayType.BALANCE]: 'BALANCE_PAY',
}

// 计算属性：格式化倒计时时间
const formattedTime = computed(() => {
  const minutes = Math.floor(remainingTime.value / 60)
  const seconds = remainingTime.value % 60
  return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
})

// 计算属性：格式化支付金额
const formattedAmount = computed(() => {
  return (totalAmount.value / 100).toFixed(2)
})

// 用户菜单命令处理
const handleUserCommand = (command: string) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'logout':
      userStore.logout()
      ElMessage.success('已退出登录')
      router.push('/')
      break
  }
}

// 支付方式选择
const selectPayment = (type: number) => {
  // 根据后端接口，目前只支持余额支付 (PayType.BALANCE = 3)
  if (type !== PayType.BALANCE) {
    ElMessage.warning('抱歉，目前只支持余额支付。')
    selectedPaymentType.value = null // 清除选择
    return
  }
  selectedPaymentType.value = type
}

// 模拟支付处理 -> 实际支付处理
const handlePay = async () => {
  if (!selectedPaymentType.value) {
    ElMessage.warning('请选择支付方式')
    return
  }

  if (totalAmount.value <= 0) {
    ElMessage.error('支付金额必须大于0')
    return
  }

  // 1. 生成支付单
  try {
    ElMessage.info('正在生成支付单...')
    const applyPayResponse = await applyPayOrder({
      bizOrderNo: orderId.value, // 业务订单号即是当前订单ID
      payType: selectedPaymentType.value,
      amount: totalAmount.value, // 支付金额，单位为分
      payChannelCode: payChannelCodeMap[selectedPaymentType.value as PayType],
      orderInfo: JSON.stringify(orderDetails.value.map(item => ({
        itemId: item.itemId,
        name: item.name,
        price: item.price,
        quantity: item.num,
        image: item.image,
        spec: item.spec
      }))),
    })

    console.log('支付单创建响应:', applyPayResponse) // 添加调试日志

    if (applyPayResponse.data && applyPayResponse.data.code === 200 && applyPayResponse.data.data) {
      // 确保支付单ID是字符串类型，避免数字精度问题
      const payOrderIdStr = applyPayResponse.data.data.toString()
      console.log('支付单ID (字符串):', payOrderIdStr) // 添加调试日志

      ElMessage.success('支付单生成成功，正在尝试支付...')

      // 2. 根据支付方式进行支付 (目前只支持余额支付)
      if (selectedPaymentType.value === PayType.BALANCE) {
        // 传递空的请求体，因为后端会从路径参数获取ID
        await tryPayOrderByBalance(payOrderIdStr, {})
        ElMessage.success('余额支付成功！')
        router.push('/orders') // 跳转到订单列表
      } else {
        // 理论上这里不会执行，因为在selectPayment中已限制
        ElMessage.warning('抱歉，目前只支持余额支付。')
      }

    } else {
      console.error('生成支付单失败响应:', applyPayResponse)
      ElMessage.error(applyPayResponse.data?.msg || '生成支付单失败')
    }
  } catch (error) {
    console.error('支付处理失败:', error)
    ElMessage.error('支付失败！')
  }
}

// 倒计时逻辑
const startCountdown = () => {
  if (timer) clearInterval(timer)
  timer = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--
    } else {
      clearInterval(timer)
      ElMessageBox.alert('支付时间已到，订单已自动取消。', '支付超时', {
        confirmButtonText: '确定',
        callback: () => {
          router.push('/orders') // 超时后跳转到订单列表
        }
      })
    }
  }, 1000)
}

// 加载订单信息
const loadOrderInfo = async () => {
  const currentOrderId = route.query.orderId as string
  const queryTotalAmount = route.query.totalAmount as string

  if (currentOrderId) {
    orderId.value = currentOrderId

    // 尝试从路由参数获取totalAmount
    if (queryTotalAmount) {
      const parsedAmount = parseInt(queryTotalAmount)
      if (!isNaN(parsedAmount)) {
        totalAmount.value = parsedAmount
        return // 如果从路由参数获取成功，则不再调用API
      }
    }

    // 如果没有从路由参数获取到，或者获取到的不是有效数字，则调用API
    try {
      const response = await queryOrderDetail(currentOrderId)
      if (response.data.code === 200) {
        totalAmount.value = response.data.data?.totalFee || 0
        orderDetails.value = response.data.data?.items || []
      } else {
        console.error('查询订单详情失败:', response)
        ElMessage.error(response.data.msg || '查询订单详情失败')
      }
    } catch (error) {
      console.error('加载订单信息失败:', error)
      ElMessage.error('加载订单信息失败')
    }
  } else {
    ElMessage.error('缺少订单ID，无法进行支付')
    router.push('/orders')
  }
}

onMounted(() => {
  // 检查用户是否已登录
  if (!userStore.token) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  loadOrderInfo()
  startCountdown()
})

onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})
</script>

<style scoped>
.pay-page {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  background: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
  padding: 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo h1 {
  color: #409eff;
  margin: 0;
  font-size: 24px;
  font-weight: bold;
}

.nav-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}

.main-content {
  flex: 1;
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.pay-card {
  width: 100%;
  max-width: 600px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.countdown {
  font-size: 14px;
  color: #f56c6c;
  font-weight: normal;
}

.countdown .time {
  font-size: 16px;
  font-weight: bold;
}

.order-info {
  text-align: center;
  margin: 20px 0;
}

.order-info h3 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 22px;
}

.order-info p {
  margin: 0;
  font-size: 16px;
  color: #666;
}

.order-info .amount {
  font-size: 24px;
  color: #f56c6c;
  font-weight: bold;
  margin-left: 5px;
}

.payment-options {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 20px;
}

.payment-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px 20px;
  border: 2px solid #e0e0e0;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 16px;
  color: #333;
  justify-content: space-between;
}

.payment-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.payment-item.selected {
  border-color: #409eff;
  background-color: #e6f7ff;
}

.payment-logo {
  width: 100px;
  height: 100px;
  object-fit: contain;
}

.payment-item .el-icon {
  font-size: 24px;
  color: #409eff;
}

.payment-item .el-icon:first-child { /* For Money icon */
  font-size: 30px;
  color: #67c23a; /* Green for balance */
}

.pay-button {
  width: 100%;
  margin-top: 30px;
}

/* 响应式 */
@media (max-width: 768px) {
  .main-content {
    padding: 10px;
    margin: 10px auto;
  }
  .pay-card {
    padding: 15px;
  }
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  .countdown {
    font-size: 13px;
  }
  .order-info h3 {
    font-size: 18px;
  }
  .order-info .amount {
    font-size: 20px;
  }
  .payment-item {
    font-size: 14px;
    padding: 12px 15px;
  }
  .payment-logo {
    width: 30px;
    height: 30px;
  }
}
</style>
